package com.bitcoin.scheduler.websocket.client.gateio.domain;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;

public class KlineQueryDeserializer extends JsonDeserializer<KlineQueryResponse> {

    @Override
    public KlineQueryResponse deserialize(JsonParser jp, DeserializationContext ctx) throws IOException {
        ObjectCodec oc = jp.getCodec();
        JsonNode node = oc.readTree(jp);

        KlineQueryResponse response = new KlineQueryResponse();

        // Parse header
        response.setId(node.get("id").asInt());
        response.setError(node.get("error").asText());
        // Parse candlestick data
        JsonNode resultList = node.get("result");
        List<KlineResult> klineResultList = Lists.newArrayList();
        for (JsonNode result : resultList) {
            KlineResult klineResult = new KlineResult();
            klineResult.setTime(Date.from(Instant.ofEpochSecond(result.get(0).asLong())));
            klineResult.setOpen(BigDecimal.valueOf(result.get(1).asDouble()));
            klineResult.setClose(BigDecimal.valueOf(result.get(2).asDouble()));
            klineResult.setHighest(BigDecimal.valueOf(result.get(3).asDouble()));
            klineResult.setLowest(BigDecimal.valueOf(result.get(4).asDouble()));
            klineResult.setVolume(BigDecimal.valueOf(result.get(5).asDouble()));
            klineResult.setAmount(BigDecimal.valueOf(result.get(6).asDouble()));
            klineResult.setMarketName(result.get(7).asText());
            klineResultList.add(klineResult);
        }
        response.setResult(klineResultList);
        return response;
    }
}
